<?php
    // 封装数据库
    // 对数据进行操作
    class Db{
        // 属性
        private $host;
        private $root;
        private $password;
        private $database;
        private $port;
        public $conn; // 保存数据库链接
        // 构造函数的作用初始化属性
        public function __construct($root,$password,$database,$host="localhost",$port='3306')
        {
            // 初始化参数
            $this->host=$host;
            $this->root=$root;
            $this->password=$password;
            $this->database=$database;
            $this->port=$port;
            $this->connectDb();
        }
        // 连接数据库
        public function connectDb(){
            // 创建数据库
            $this->conn=mysqli_connect($this->host,$this->root,$this->password,$this->database,$this->port);
            // 判断数据库是否链接成功
            if($this->conn){
                echo '数据库链接成功'."<br>";
            }else{
                echo "数据库链接失败".mysqli_error($this->conn);
                return;
            }
        }
        // 增加数据
        public function write(){
           $sql = "insert into user values('2','张','10')";
           $result = mysqli_query($this->conn,$sql);
        //    echo mysqli_affected_rows();
        //    if (mysqli_query($this->conn,$sql)){
        //         echo "插入成功";
        //    }else{
        //         echo "插入失败".mysqli_error($this->conn);
        //    };
        }
        // 修改
        public function edit($sql){
            if(mysqli_query($this->conn,$sql)){
                echo "修改成功";
            }else{
                echo "修改失败".mysqli_error($this->conn);
            }
        }
        // 查询
        // public function querys($sql1){
            
        //     if(mysqli_query($this->conn,$sql1)){
        //         echo "查询成功";
        //     }else{
        //         echo "查询失败".mysqli_error($this->conn);
        //     }
        // }

        public function select(){
            $sql = "SELECT * FROM USER";
            $result = mysqli_query($this->conn,$sql);
            if(mysqli_num_rows($result)>0){
                return mysqli_fetch_all($result);
            }
        }
        // 删除
        public function del(){
            $sql = "DELETE FROM `test`.`user` WHERE `id` = '1'";
            if(mysqli_query($this->conn,$sql)){
                echo "删除成功";
            }else{
                echo "删除失败".mysqli_error($this->conn);
            }
        }
    }
    $db =new Db("root","root","test","127.0.0.1");
    $sql = "UPDATE USER SET `name` = '嗷呜',`age` = '20' WHERE `id` ='2'";
    // var_dump($db);   
    // $db->write();
    // $db->edit($sql);
    $db->select();
    // $db->del();
?> 